package com.itheima.web;

import com.itheima.dto.OrderDTO;
import com.itheima.service.OrderService;
import com.itheima.support.Result;
import com.itheima.vo.OrderVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/order")
public class OrderController {

    @DubboReference
    private OrderService orderService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    //发消息，生成者，消费者在Service里面
    @GetMapping("/sendSms/{telephone}")
    public Result<Boolean> sendSms(@PathVariable("telephone") String telephone) {

        //void convertAndSend(String exchange, String routingKey, Object message) throws AmqpException;
        amqpTemplate.convertAndSend("sms_exchange", "sms", telephone);
        return Result.build(true);
    }

    @PostMapping("/add")
    public Result<Long> add(@RequestBody OrderVO orderVO) {
        Long orderId = orderService.add(orderVO);
        MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置ttl
                message.getMessageProperties().setExpiration("10000");
                return message;
            }
        };
        amqpTemplate.convertAndSend("pay_exchange", "pay", orderId, messagePostProcessor);
        return Result.build(orderId);
    }

    @GetMapping("/successOrder/{orderId}")
    public Result<OrderDTO> successOrder(@PathVariable("orderId") Long orderId) {
        return Result.build(orderService.successOrder(orderId));
    }

}
